import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_aygsh/entity/common_entity.dart';
import 'package:flutter_aygsh/entity/user_receipt_entity.dart';
import 'package:flutter_aygsh/liz_mine/Invoice/chooseInvoice.dart';
import 'package:flutter_aygsh/liz_mine/order/LocalNavWebWidget.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../base/Constant.dart';
import '../../entity/order_list_entity.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/SignUtil.dart';
import 'MyHome.dart';
import 'OrderComment.dart';
import 'OrderDetailPage.dart';
import 'OrderPay.dart';

class AllOrderPage extends StatefulWidget {
  var type;
  AllOrderPage({Key key, @required this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return AllOrderView();
  }
}

// 订单状态
// 1待付款
// 2已付款、待发货
// 3已发货、待确认收货
// 4已确认收货、待评价
// 5已完成
// 6退换货

class AllOrderView extends State<AllOrderPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  List<OrderListDataData> dataList = List();
  int page = 1;
  String receipt_name = '';
  String invoice_id;
  EasyRefreshController _controller = new EasyRefreshController();
  String token = "";
  String backReason = "", backReason2 = "", danhao = "", order_num = "";

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Container(
      child: new Container(
        color: divideColor,
        child: new EasyRefresh(
          controller: _controller,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          child: ListView.separated(
              itemBuilder: _renderRow,
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  color: divideColor,
                  height: 5,
                );
              },
              itemCount: dataList == null ? 0 : dataList.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  loadListLog() async {
    Map map = new Map();
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/Logistics/getList",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    CommonEntityEntity homeListEntity =
        new CommonEntityEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        logs.addAll(homeListEntity.data.datas);
        for (int i = 0; i < logs.length; i++) {
          PickerData.add("\"" + logs[i].title + "\"");
        }
      });
  }

  var PickerData = [];
  String bank_id = "", name = "选择快递", time1 = "开始日期", time2 = "结束日期";
  List<CommonEntityDataData> logs = new List();

  var myState1;
  showCate() {
    new Picker(
        adapter: PickerDataAdapter<String>(
            pickerdata: new JsonDecoder().convert(PickerData.toString())),
        hideHeader: true,
        title: new Text("选择快递"),
        cancelText: "取消",
        cancelTextStyle: TextStyle(color: Colors.grey),
        confirmText: "确定",
        confirmTextStyle: TextStyle(color: mainColor),
        onConfirm: (Picker picker, List value) {
          bank_id = logs[value[0]].id;
          // controller.text = name;
          name = picker.getSelectedValues()[0];
          myState1(() {});
        }).showDialog(context);
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return new OrderDetailPage(
            id: dataList[index].id,
          );
        }));
      },
      child: new Container(
        margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_15)),
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(10)),
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Text("订单号: " + dataList[index].order_num,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: Colors.grey)),
                ),
                Text(
                    dataList[index].status == '1'
                        ? '待支付'
                        : dataList[index].status == '2'
                            ? '待发货'
                            : dataList[index].status == '3'
                                ? '待收货'
                                : dataList[index].status == '4'
                                    ? '待评价'
                                    : dataList[index].status == '5'
                                        ? '已完成'
                                        : '退换货',
                    style: TextStyle(
                        color: mainColor,
                        fontSize:
                            ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)))
              ],
            ),
            Container(
              height: 10,
            ),
            Container(
              child: ListView.builder(
                padding: EdgeInsets.all(0),
                physics: new NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index1) {
                  return GestureDetector(
                      onTap: () {},
                      child: Container(
                          margin: EdgeInsets.all(10),
                          child: Column(
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  ClipRRect(
                                      borderRadius: BorderRadius.circular(2),
                                      child: CachedNetworkImage(
                                        width: ScreenUtil.getInstance()
                                            .setHeight(DP_120),
                                        fit: BoxFit.fill,
                                        height: ScreenUtil.getInstance()
                                            .setHeight(DP_120),
                                        imageUrl: Api.ImgBaseUrl +
                                            dataList[index].datas[index1].img,
                                        placeholder: (context, url) =>
                                            Image.asset(
                                                'images/pic_default.png',
                                                width: ScreenUtil.getInstance()
                                                    .setHeight(DP_120),
                                                fit: BoxFit.fill,
                                                height: ScreenUtil.getInstance()
                                                    .setHeight(DP_120)),
                                        errorWidget: (context, url, error) =>
                                            Image.asset(
                                                'images/pic_default.png',
                                                width: ScreenUtil.getInstance()
                                                    .setHeight(DP_120),
                                                fit: BoxFit.fill,
                                                height: ScreenUtil.getInstance()
                                                    .setHeight(DP_120)),
                                      )),
                                  Container(
                                    width: 10,
                                  ),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                            dataList[index]
                                                .datas[index1]
                                                .goods_name,
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(
                                                            SMALL_FONT_SIZE))),
                                        Container(
                                          height: 4,
                                        ),
                                        Container(
                                          width: (MediaQuery.of(context)
                                                  .size
                                                  .width -
                                              ScreenUtil.getInstance()
                                                  .setHeight(DP_250)),
                                          child: Html(
                                              data: dataList[index]
                                                  .datas[index1]
                                                  .sku_str,
                                              defaultTextStyle: TextStyle(
                                                  color: Colors.black45,
                                                  fontSize: ScreenUtil
                                                          .getInstance()
                                                      .setSp(SMALL_FONT_SIZE))),
                                        ),
                                        Container(
                                          height: 6,
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Text(
                                                MONEY +
                                                    dataList[index]
                                                        .datas[index1]
                                                        .price +
                                                    '; ',
                                                style: TextStyle(
                                                    color: black,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE))),
                                            // Container(
                                            //   width:
                                            //       (MediaQuery.of(context).size.width -
                                            //           ScreenUtil.getInstance()
                                            //               .setHeight(DP_350)),
                                            // ),
                                            Text(
                                                "x" +
                                                    dataList[index]
                                                        .datas[index1]
                                                        .num,
                                                style: TextStyle(
                                                    color: black,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            SMALL_FONT_SIZE))),
                                          ],
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ],
                          )));
                },
                itemCount: dataList[index].datas.length,
                shrinkWrap: true,
              ),
            ),
            Container(
              height: 10,
            ),
            Container(
                width: double.infinity,
                alignment: Alignment.centerRight,
                child: RichText(
                    text: TextSpan(children: [
                  TextSpan(
                      text: "共" +
                          dataList[index].datas.length.toString() +
                          '件商品 ',
                      style: TextStyle(
                          color: Colors.grey,
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                  TextSpan(
                      text: "订单金额 ¥" +
                          formatNum(
                              (double.parse(dataList[index].allprice)),
                              2),
                      style: TextStyle(
                          color: black,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                ]))),
            Container(
              height: 10,
            ),
            // Text(
            //     "收货人: " +
            //         dataList[index].consignee.toString() +
            //         "   " +
            //         dataList[index].contact_number.toString(),
            //     style: TextStyle(
            //         color: black_99,
            //         fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),

            // Container(
            //   height: 10,
            // ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Offstage(
                  offstage: dataList[index].status != "1",
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          border: Border.all(color: black_99, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('取消订单',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: black_99)),
                    ),
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (context) => new AlertDialog(
                          title: new Text('提示'),
                          content: new Text('确定取消该条订单吗，取消后不可撤回'),
                          actions: <Widget>[
                            new FlatButton(
                              onPressed: () => Navigator.of(context).pop(false),
                              child: new Text(
                                '取消',
                                style: TextStyle(color: Colors.grey),
                              ),
                            ),
                            new FlatButton(
                              onPressed: () {
                                Navigator.of(context).pop(false);
                                cancle(index);
                              },
                              child: new Text('确定取消',
                                  style: TextStyle(color: mainColor)),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "1",
                  child: GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(left: 10),
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('支付订单',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor)),
                    ),
                    onTap: () {
                      Navigator.of(context)
                          .push(MaterialPageRoute(builder: (context) {
                        return new OrderPayPage(
                            orderId: dataList[index].id,
                            title: '商品支付',
                            discount: dataList[index].discount,
                            orderNum: dataList[index].order_num,
                            totalMoney:
                                (double.parse(dataList[index].allprice) -
                                        double.parse(dataList[index].discount))
                                    .toString());
                      }));
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "3",
                  child: GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(right: 10),
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('查看物流',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor)),
                    ),
                    onTap: () {
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (context) {
                        return new MyHomePage(
                          title: dataList[index].logistics + "",
                          express_number: dataList[index].express_number + "",
                        );
                      }));
                      // Fluttertoast.showToast(msg: "敬请期待");
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "3",
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          color: mainColor,
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('确认收货',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: white)),
                    ),
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (context) => new AlertDialog(
                          title: new Text('提示'),
                          content: new Text('确定已经收到货物吗,确认后不可撤回'),
                          actions: <Widget>[
                            new FlatButton(
                              onPressed: () => Navigator.of(context).pop(false),
                              child: new Text(
                                '取消',
                                style: TextStyle(color: Colors.grey),
                              ),
                            ),
                            new FlatButton(
                              onPressed: () {
                                Navigator.of(context).pop(false);
                                confirm(index);
                              },
                              child: new Text('确定',
                                  style: TextStyle(color: mainColor)),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "2" &&
                      dataList[index].status != "4" &&
                      dataList[index].status != "5" &&
                      dataList[index].status != "8",
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          color: mainColor,
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('申请退货',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: white)),
                    ),
                    onTap: () {
                      showCupertinoDialog(
                          context: context,
                          builder: (context) {
                            return CupertinoAlertDialog(
                              title: Text('请输入退货原因'),
                              content: Card(
                                elevation: 0.0,
                                child: Column(
                                  children: <Widget>[
                                    TextField(
                                      onChanged: (value) {
                                        backReason = value;
                                      },
                                      maxLines: 4,
                                      minLines: 4,
                                      cursorColor: mainColor,
                                      decoration: InputDecoration(
                                          hintText: '输入原因',
                                          border: InputBorder.none,
                                          filled: true,
                                          fillColor: Colors.grey.shade50),
                                    ),
                                  ],
                                ),
                              ),
                              actions: <Widget>[
                                CupertinoDialogAction(
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                  child: Text('取消',
                                      style: TextStyle(color: black_99)),
                                ),
                                CupertinoDialogAction(
                                  onPressed: () {
                                    Navigator.pop(context);
                                    // editName();
                                    submit(index);
                                  },
                                  child: Text('确定',
                                      style: TextStyle(color: mainColor)),
                                ),
                              ],
                            );
                          });
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "7" ||
                      (dataList[index].refund_express_number != null &&
                          dataList[index].refund_express_number != "null"),
                  child: GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(right: 10),
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('填写退货快递单号',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor)),
                    ),
                    onTap: () {
                      showCupertinoDialog(
                          context: context,
                          builder: (context) {
                            return StatefulBuilder(builder: (context, myState) {
                              myState1 = myState;
                              return CupertinoAlertDialog(
                                title: Text('请输入快递单号'),
                                content: Card(
                                  elevation: 0.0,
                                  child: Column(
                                    children: <Widget>[
                                      GestureDetector(
                                        onTap: () {
                                          showCate();
                                        },
                                        child: Container(
                                          color: white,
                                          padding: EdgeInsets.all(10),
                                          child: Row(
                                            children: <Widget>[
                                              Expanded(
                                                child: Text('$name',
                                                    style: TextStyle(
                                                        fontSize: 14,
                                                        color: black)),
                                              ),
                                              Icon(Icons.arrow_forward_ios,
                                                  size: 16)
                                            ],
                                          ),
                                        ),
                                      ),
                                      TextField(
                                        onChanged: (value) {
                                          danhao = value;
                                        },
                                        maxLines: 1,
                                        minLines: 1,
                                        cursorColor: mainColor,
                                        decoration: InputDecoration(
                                            hintText: '输入快递单号',
                                            border: InputBorder.none,
                                            filled: true,
                                            fillColor: Colors.grey.shade50),
                                      ),
                                    ],
                                  ),
                                ),
                                actions: <Widget>[
                                  CupertinoDialogAction(
                                    onPressed: () {
                                      Navigator.pop(context);
                                    },
                                    child: Text('取消',
                                        style: TextStyle(color: black_99)),
                                  ),
                                  CupertinoDialogAction(
                                    onPressed: () {
                                      if (danhao == "") {
                                        Fluttertoast.showToast(msg: "请输入快递单号");
                                        return;
                                      }
                                      Navigator.pop(context);
                                      // editName();
                                      submitDanHao(index);
                                    },
                                    child: Text('确定',
                                        style: TextStyle(color: mainColor)),
                                  ),
                                ],
                              );
                            });
                          });
                      // Fluttertoast.showToast(msg: "敬请期待");
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "4",
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          color: mainColor,
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('评价',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: white)),
                    ),
                    onTap: () {
                      if (Platform.isAndroid) {
                        Navigator.of(context)
                            .push<String>(MaterialPageRoute(builder: (context) {
                          return new LocalNavWebWidget(
                              Api.URL_Comment +
                                  'token=' +
                                  token +
                                  '&order_id=' +
                                  dataList[index].id,
                              "订单评价");
                        })).then((value) {
                          if (value != null) {
                            Fluttertoast.showToast(msg: '评价成功');
                            page = 1;
                            loadList();
                          }
                        });
                        return;
                      }
                      Navigator.of(context)
                          .push<String>(MaterialPageRoute(builder: (context) {
                        return OrderCommentPage(
                            url: Api.URL_Comment +
                                'token=' +
                                token +
                                '&order_id=' +
                                dataList[index].id);
                      })).then((value) {
                        if (value != null) {
                          Fluttertoast.showToast(msg: '评价成功');
                          page = 1;
                          loadList();
                        }
                      });
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "4" &&
                      dataList[index].status != "5",
                  child: dataList[index].invoice_id != "Y"
                      ? Center()
                      : GestureDetector(
                          child: Container(
                            margin: EdgeInsets.only(left: 10),
                            padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                            decoration: BoxDecoration(
                                border: Border.all(color: mainColor, width: 1),
                                borderRadius: BorderRadius.circular(30)),
                            child: Text('申请开票',
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE),
                                    color: mainColor)),
                          ),
                          onTap: () {
                            Navigator.of(context).push<UserReceiptListDataData>(
                                MaterialPageRoute(builder: (context) {
                              return ChooseReceiptPage();
                            })).then((UserReceiptListDataData data) {
                              print(data.purchaser);
                              print(data.invoice_id);
                              if (data == null) {
                                return;
                              }
                              receipt_name = data.purchaser;
                              invoice_id = data.invoice_id;
                              //  coupon_name = coupon['money'].toString() + '元';
                              //  coupon_record_id = coupon['coupon_record_id'].toString();
                              //  coupon_money= coupon['money'].toString();
                              setState(() {});
                              showDialog(
                                context: context,
                                builder: (context) => new AlertDialog(
                                  title: new Text('确认提示'),
                                  content: new Text('确定选择该发票抬头吗，确认后不可撤回?'),
                                  actions: <Widget>[
                                    new FlatButton(
                                      onPressed: () =>
                                          Navigator.of(context).pop(false),
                                      child: new Text(
                                        '取消',
                                        style: TextStyle(color: Colors.grey),
                                      ),
                                    ),
                                    new FlatButton(
                                      onPressed: () {
                                        Navigator.of(context).pop(false);
                                        applyInvoice(dataList[index].id);
                                      },
                                      child: new Text('确定完成',
                                          style: TextStyle(color: mainColor)),
                                    ),
                                  ],
                                ),
                              );
                            });
                          },
                        ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  submit(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = dataList[index].id;
    String ids = "", ids2 = "";
    for (int i = 0; i < dataList[index].datas.length; i++) {
      ids += dataList[index].datas[i].order_detail_id + ",";
      ids2 += dataList[index].datas[i].goods_id + ",";
    }
    map['goodsId_str'] = ids2.substring(0, ids2.length - 1);
    map['order_detail_id_str'] = ids.substring(0, ids.length - 1);
    map['drawback_reason'] = backReason;
    map['sign_type'] = "dmayg.Order.applyDrawback";
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/Order/applyDrawback",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    loadListLog();
    getString(TOKEN).then((value) {
      token = value;
      if (token == null) {
        return;
      }
      loadList();
    });
  }

  submitDanHao(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = dataList[index].id;
    map['express_number'] = danhao;
    map['sign_type'] = "dmayg.Order.fillInRefundExpressNum";
    map['logistics'] = name;
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/Order/fillInRefundExpressNum",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      // dataList[index](index);
      dataList[index].refund_express_number = danhao;
      setState(() {});
    }
  }

  applyInvoice(String order_id) async {
    Map map = new Map();
    map['sign_type'] = createSignType(Api.URL_INVOICE_APPLY);
    map['invoice_id'] = invoice_id.toString();
    map['token'] = token;
    map['order_id'] = order_id.toString();
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_INVOICE_APPLY, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    print(userMap);
    if (code == 1) {
      page = 1;
      loadList();
      Fluttertoast.showToast(msg: '申请开票成功');
      // Toast.toast(context, msg: '申请开票成功');
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed)
      getString(TOKEN).then((value) {
        token = value;
      });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    if (widget.type.toString() == '0') {
      map['status'] = '';
    } else {
      map['status'] = widget.type.toString();
    }

    map['p'] = page.toString();
    map['per'] = '10';
    map['sign_type'] = createSignType(Api.URL_ORDER_LIST);
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_ORDER_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    OrderListEntity homeListEntity = new OrderListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data);
        } else {
          dataList.addAll(homeListEntity.data);
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(noMore: homeListEntity.data.length == 0);
          if (homeListEntity.data.length == 0) {
            Fluttertoast.showToast(msg: "暂无更多数据");
          }
        }
      });
  }

  del(id) async {
    // FormData formData = new FormData.fromMap({
    //   "token": token,
    //   "id": id,
    // });
    // Response<String> response =
    //     await HttpUtil().post(Api.DEL_ORDER, data: formData);
    // Map userMap = json.decode(response.data);
    // int code = userMap["code"];
    // String msg = userMap["msg"];
    // Navigator.of(context).pop(1);
    // Fluttertoast.showToast(msg: msg);
    // if (code == 0) {
    //   page = 1;
    //   loadList();
    // }
    // return true;
  }
  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }

  confirm(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = dataList[index].id;
    map['sign_type'] = createSignType(Api.URL_ORDER_CONFIRM);
    Response<String> response =
        await HttpUtil().post(Api.URL_ORDER_CONFIRM, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
    return true;
  }

  cancle(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = dataList[index].id.toString();
    map['sign_type'] = createSignType(Api.URL_ORDER_CANCEL);
    Response<String> response =
        await HttpUtil().post(Api.URL_ORDER_CANCEL, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
    return true;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
